﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WebBrowserTest.AnalyzeResults;

namespace WebBrowserTest.Analyzers
{
    public class GoogleIndexAnalyzer : AbstractAnalyzer
    {
        private string _additExpr = "<div>([0-9,]+) results</div>";
        public string LookupExpression
        {
            get { return _lookupExpr; }
            set { _lookupExpr = value; }
        }
        public string AdditionalExpression
        {
            get { return _additExpr; }
            set { _additExpr = value; }
        }
        public GoogleIndexAnalyzer()
        {
            _lookupExpr = "<div id=resultStats>About ([0-9,]+) results<nobr>";
        }

        public override AbstractAnalyzeResult GetAnalyseResult(string html, string url)
        {
            var matches = Regex.Matches(html, LookupExpression);
            if(matches.Count == 0)
            {
                matches = Regex.Matches(html, AdditionalExpression);
            }
            var indexedResults = 0;
            for (var i = 0; i < matches.Count; i++)
            {
                var backLinksVal = matches[i].Groups[1].Value.Replace(",", "");
                
                if (int.TryParse(backLinksVal, out indexedResults))
                {
                    break;
                }
            }
            return new DefaultResult { Value = indexedResults, DomainName = url, Date = DateTime.Now };
        }
    }
}
